// pages/index/welcome.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
  },
  onGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      e.detail.userInfo.add_time = new Date()
      console.log(e.detail.userInfo)
      const db = wx.cloud.database()
      db.collection('userInfo').add({
      data: e.detail.userInfo,
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        this.setData({
          userInfo: e.detail.userInfo
        })
        
      },
      fail: err => {
        console.error(err)
      }
    })
    }
  },
  onLoad() {

    var that = this
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        app.globalData.openid = res.result.openid
        wx.setStorageSync('openid', res.result.openid)
        const db = wx.cloud.database()
        db.collection('userInfo').where({
          _openid: res.result.openid
        }).get({
          success: res=>{
            that.setData({
              userInfo: res.data[0]
            })
          }, 
          fail: err => {
            wx.showToast({
              icon: 'none',
              title: '查询记录失败'
            })
          }
        })
        
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })

  },

  goSign() {
    var returnUrl = wx.getStorageSync('returnUrl')
    if(returnUrl){
      wx.removeStorageSync('returnUrl')
      wx.reLaunch({
        url: returnUrl,
      })
    }else{
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
    
  }
})